#!/usr/bin/env bash
# Copyright (c) 2021 Open Compute Project
# Copyright [2023] Hewlett Packard Enterprise Development LP
#     Modified: added SLE support to the remake shell script with supporting docs
set -euo pipefail

DIST="$(awk -F= '/^NAME/{print tolower($2)}' /etc/os-release|awk 'gsub(/[" ]/,x) + 1')"

KVER=$(uname -r)
default_install=1

if [ "$*" == "install" ]; then
    INSTALL=1
fi

case "$DIST" in
    debian*|ubuntu)
        KDIR=/usr/src/linux-${KVER}
        ;;
    centos*)
        KDIR=/usr/src/kernels/${KVER}
        ;;
    oraclelinux*)
        KDIR=/usr/src/kernels/${KVER}
        ;;
    sle*)
        KDIR=/usr/src/linux-${KVER%-default}
        # In SUSE Linux Enterprise products, loading unsupported modules is disabled by default
        # at present, this driver is not supported by SUSE, but does work once compiled and loaded in unsupported mode
        if ! grep -q 'allow_unsupported_modules 1' /etc/modprobe.d/10-unsupported-modules.conf \
            || ! [ -f /etc/modprobe.d/10-unsupported-modules.conf ]; then

            >&2 echo "$DIST requires allow_unsupported_modules to be set for this driver"
            exit 1
        fi
        ;;
esac

if [ -e ./ksrc ]; then
    KDIR=./ksrc
    default_install=0
fi

if [ ! -d "${KDIR:-}" ]; then
    echo "Could not locate kernel source for distribution '$DIST'"
    exit 1
fi

make -C "${KDIR}" M="${PWD}"

if [ "${INSTALL:-$default_install}" == 1 ]; then
    echo "installing module"
    ln -sf "${PWD}"/ptp_ocp.ko /lib/modules/"${KVER}"
    depmod -a
fi
